﻿using com.guojin.core.io.message;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using com.guojin.mj.net.message.login;
using com.guojin.mj.net.message.game;
using com.guojin.mj.net.message;
using System;

public class GameRoomController : MonoBehaviour
{
    private static GameRoomController instance;
    public static GameRoomController GetInstance()
    {
        if (instance == null)
        {
            instance = new GameRoomController();
        }
        return instance;
    }

    private  GameRoomInfoRet gri;

    //加载房间信息
    public void OnReceiveMsg127(string msg, Message data)
    {
         gri = (GameRoomInfoRet) data;

        DelePageBeforeLoadGameRoomPage();
       
        UIManager.ChangeUI(UIManager.PageState.GameRoomPage,
            obj =>
            {
                obj.GetComponent<GameRoomPage>().InformationSetting();
                InitRoomInfo();
            });
    }

    private void DelePageBeforeLoadGameRoomPage()
    {
        if (GameObject.Find("GameRoomPage(Clone)"))
            GameObject.Find("GameRoomPage(Clone)").GetComponent<GameRoomPage>().CloseBtnClick();

        if (GameObject.Find("CreatRoomPage(Clone)"))
            GameObject.Find("CreatRoomPage(Clone)").GetComponent<CreateRoomPage>().CloseBtnClick();

        if(GameObject.Find("TrusteeShipPage(Clone)"))
           GameObject.Find("TrusteeShipPage(Clone)").GetComponent<TruesteeShipPage>().CloseBtnClick();
    }

    private void InitRoomInfo()
    {
        if (gri != null)
            StartInitRoomInfo(gri);
        else
            Debug.Log("GameRoomController中保存的GameRoomInfoRet消息为null");
    }

    private void StartInitRoomInfo(GameRoomInfoRet GTI)
    {
        GameRoomModel.GetInstance().SaveRoomInfoToGameRoomModel(GTI.roomType, GTI.roomID, 
            GTI.currentUserNum, GTI.maxUser, GTI.currentChapterNum, GTI.maxChapterNum, GTI.state, GTI.trusteeshipTime);              //生成房间信息

        SaveToPlayerPrefsAndShowRuleInPage(GTI.options);              //生成规则

        GetPlayerLocationFromGameUser(GTI.gameUser);

        GameController.GetInstance().InitPlayerPosition();                  //根据玩家location生成位置数组

        GameRoomModel.GetInstance().GameStartAppendPlayersToPlayerDic(GTI.gameUser);                           //生成头像

        if (GTI.chapter.state == 0)
        {
            SetBtnStateBeforeGameStart();
        }
        else
        {
            InitChapterInfo(GTI.chapter);
            InitAllPlayerUserChapterInfo(GTI.chapter.userChapterInfo);                                                                    //生成玩家下注信息

            if (GTI.chapter.state == 1)
            {
                SetBetInfo(GTI);
            }
            else
            {
                ChapterEndController.GetInstance().ChapterEndSetChapterUserInfo(GTI.chapter);
                ChapterEndController.GetInstance().ShowChapterEndPage(GTI.chapter);
                CheckShowReadyBtn();
            }                                                                                                          
        }                                                                                                                    
    }

    private void SetBtnStateBeforeGameStart()
    {
            CheckReadyAndStartBtnState();
            CheckInviteBtnState();
    }

    private void InitChapterInfo(ChapterInfoRet chapter )
    {
        Debug.Log("断线重连传来房间状态：" + chapter.state.ToString());
        Debug.Log("断线重连传来聚锅" + chapter.isJvGuo.ToString());
        Debug.Log("断线重连传来总赌注：" + chapter.currentTotalBet.ToString());
        Debug.Log("断线重连传来单注数" + chapter.currentSingleBet.ToString());
        GameRoomModel.GetInstance().RoomState = chapter.state;
        GameRoomModel.GetInstance().IsJvGuo = chapter.isJvGuo;
        GameRoomModel.GetInstance().MaxLimitScore = chapter.MaxLimitScore;
        GameRoomModel.GetInstance().CurrentTotalBet = chapter.currentTotalBet;
        GameRoomModel.GetInstance().CurrentSingleBet = chapter.currentSingleBet;

        if (chapter.state == 1)
        {
            GameController.GetInstance().InstantiateBet(chapter.totalBetScoreStr);       //生成赌注
        }
    }

    private void InitAllPlayerUserChapterInfo(List<UserChapterInfoRet > userChapterInfo)
    {
        for (int i = 0; i < userChapterInfo.Count; i++)
        {
            //手牌自动生成， 牌型自动显示，玩家状态,  分数自动显示； 
            GameRoomModel.GetInstance().GetPlayerFromPlayerDic(
                userChapterInfo[i].LocationIndex).InitPlayerChapterInfo(userChapterInfo[i]);
        }
    }

    private void SetBetInfo( GameRoomInfoRet GTI)
    {
        BetPageController.GetInstance().SetBetInfo(GTI.chapter.bir);
        BetPageController.GetInstance().CheckShowBetElement(GTI.chapter.bir);
    }

    private void CheckShowReadyBtn()
    {
        if (GameRoomModel.GetInstance().CurrentChapter < GameRoomModel.GetInstance().MaxChapter)
        {
            GameRoomPage.GetInstance().SetReadyBtn(1);
        }
    }

    private void ShowAllPlayerState()
    {
        //foreach (var item in GameRoomModel.GetInstance().playerDic.Values)
        //{
        //    item.ChangePlayerState();
        //}
    }

    private void GetPlayerLocationFromGameUser(List<GameUserInfoRet> gameUser)
    {
        for (int i = 0; i < gameUser.Count; i++)
        {
            if (gameUser[i].userId.ToString() == GameData.GetInstance().userID)
            {
                GameData.GetInstance().locationIndex = gameUser[i].locationIndex;
            }
        }
    }

    #region     //保存和显示规则

    private void SaveToPlayerPrefsAndShowRuleInPage(List<OptionEntry> options)
    {
        GameController.GetInstance().SaveRule(options);
        SetRuleToGameRoomPage(options);
    }

    private void SetRuleToGameRoomPage(List<OptionEntry> options)
    {
        SaveOptionsToOptionDic(options);
        SetMaxAndMinToModel();
        SetRuleToPageRuleTex1();
        SetRuleToPageRuleTex2();
    }

    private Dictionary<string, string> optionDic = new Dictionary<string, string>();
    private void SaveOptionsToOptionDic(List<OptionEntry> options)
    {
        optionDic.Clear();
        for (var i = 0; i < options.Count; i++)
            optionDic.Add(options[i].key, options[i].value);
    }

    private void SetMaxAndMinToModel()
    {
        string str = optionDic[GameController.scoreRange];
        var strArr = str.Split('-');
        GameRoomModel.GetInstance().MinScore = int.Parse(strArr[0]);
        GameRoomModel.GetInstance().MaxScore = int.Parse(strArr[1]);
    }

    private void SetRuleToPageRuleTex1()
    {
        GameRoomPage.GetInstance().SetRuleTex1(string.Format("{0}，{1}", GetMaxAndMinScore(), GetBetweenPointJvGuo()));
    }

    private void SetRuleToPageRuleTex2()
    {
        GameRoomPage.GetInstance().SetRuleTex2(string.Format("{0}，{1}", GetCardCountsStrFromCardCounts(), GetMiddleJoin()));
    }

    private string GetMaxAndMinScore()
    {
        return optionDic[GameController.scoreRange] + "分";
    }

    private string GetBetweenPointJvGuo()
    {
        if (optionDic[GameController.betweenOnePointJvGuo] == "true")
        {
            return "上下一点聚锅";
        }
        else
        {
            return "上下一点不聚锅";
        }
    }

    private  string GetCardCountsStrFromCardCounts()
    {
        switch (optionDic[GameController.cardCounts])
        {
            case "1":
                return "一副牌";
            case "2":
                return "二副牌";
            case "3":
                return "三副牌";
            case "4":
                return "四副牌";
            default:
                return "四副牌";
        }
    }

    private string GetMiddleJoin()
    {
        if (optionDic[GameController.middleJoin] == "true")
        {
            return "允许中途加入";
        }
        else
        {
            return "不允许中途加入";
        }
    }
    #endregion

    //检查设置按钮状态
    public void CheckReadyAndStartBtnState()
    {
        //if (GameData.GetInstance().locationIndex == 0)
        //{
        //    bool allReady = GameController.GetInstance().CheckAllReady();

        //    if (GameRoomModel.GetInstance().playerDic.Count >= 2 && allReady)
        //        GameRoomPage.GetInstance().SetStartBtn(1);
        //    else
        //        GameRoomPage.GetInstance().SetStartBtn(1);
        //}
        //else
        //{

            bool isReady = GameRoomModel.GetInstance().GetPlayerFromPlayerDic(GameData.GetInstance().locationIndex).IsReady;

            if (!isReady)
                GameRoomPage.GetInstance().SetReadyBtn(1);
            else
                GameRoomPage.GetInstance().SetReadyBtn(0);
        //}
    }

    public void CheckInviteBtnState()
    {
        if (GameRoomModel.GetInstance().playerDic.Count < 6)
            GameRoomPage.GetInstance().SetInviteBtn(1);
        else
            GameRoomPage.GetInstance().SetInviteBtn(0);
    }

    //点击准备 按钮调用
    public void ReadyBtnClickCallBack()
    {
        GameRoomPage.GetInstance().SetAudAndPlay(5);//声音

        //聚锅设置总赌注
        if (!GameRoomModel.GetInstance().IsJvGuo)
        {
            GameRoomModel.GetInstance().CurrentTotalBet = 0;
        }
        GameRoomModel.GetInstance().CurrentSingleBet = 0;

        //赌注预设体清除
        //TooL.DestroyAllChildren(GameObject.Find("DeskBetPoint"));

        //初始化玩家牌局信息
        foreach (var item in GameRoomModel.GetInstance().playerDic.Values)
        {
            Debug.Log("玩家" + item.locationIndex + " 手牌  和结算分恢复默认");
            item.ClickReadyInitUser();//清空手牌什么的
        }

        GameData.GetInstance().isReadyClean = true;
    }

    //开始游戏，12.3发牌时调用
    public void StartGame()
    {
        //if (GameData.GetInstance().isReadyClean == false)           //托管自动准备后断线重连，不点击准备按钮牌局开始时可能仍有上局残留。
        //{
            ReadyBtnClickCallBack();
        //}

        //取消开始，准备，邀请好友按钮
        GameRoomPage.GetInstance().SetStartBtn(0);
        GameRoomPage.GetInstance().SetReadyBtn(0);
        GameRoomPage.GetInstance().SetInviteBtn(0);

        //上限分数
        if (GameRoomModel.GetInstance().MaxLimitScore == 0)
        {
            GameRoomModel.GetInstance().MaxLimitScore = GameRoomModel.GetInstance().MaxScore;
        }

        //房间状态， 设置局数
        if (GameRoomModel.GetInstance().RoomState == 0 || GameRoomModel.GetInstance().RoomState == 2)
        {
            GameRoomModel.GetInstance().RoomState = 1;
        }
        GameRoomModel.GetInstance().CurrentChapter += 1;


        //玩家取消头像上的准备,已经准备改为false    //所有玩家下底注
        foreach (var item in GameRoomModel.GetInstance().playerDic.Values)
        {
            item.IsReady = false;
            item.isOut = false;
            item.isMiddleJoin = false;
           // item.ChangePlayerState();
            item.PlayerBet(GameRoomModel.GetInstance().MinScore);           
        }

       
    }

    //解散房间
    public void OnReceiveMsg73(string msg, Message data)
    {
        var dr = (DissolveRoomRet)data;

        if (dr.roomID != GameRoomModel.GetInstance().RoomID)
        {
            Debug.Log("解散消息不是当前房间" + dr.roomID);
            return;
        }

        if (GameObject.Find("VoteDissolveRoomPage(Clone)"))
            GameObject.Find("VoteDissolveRoomPage(Clone)").GetComponent<VoteDissolveRoomPage>().CloseBtnClick();

            DissloveRoom();
    }

    private void DissloveRoom()
    {
        if (GameRoomModel.GetInstance().RoomState == 0)
        {
            if (GameObject.Find("GameRoomPage(Clone)"))
                GameController.GetInstance().DeleteAllExceptGameHall();
            else
                Debug.Log("没有找到GameRoomPage面板，RoomState == 0");
        }
        else if (GameRoomModel.GetInstance().RoomState != 0 )
        {
            if (GameObject.Find("GameRoomPage(Clone)"))
            {
                UIManager.ChangeUI(UIManager.PageState.GameEndPage, (GameObject obj) =>
                {
                    obj.GetComponent<GameEndPage>().InformationSetting();
                });
            }
            else
                Debug.Log("没有找到GameRoomPage面板，RoomState != 0");
        }
    }

    //退出房间
    public void OnReceiveMsg75(string msg, Message data)
    {
        var er = (ExitRoomRet)data;

        if (er.roomID != GameRoomModel.GetInstance().RoomID)
        {
            Debug.Log("退出消息不是当前房间" + er.roomID);
            return;
        }
        else
        {
            ExitRoom(er.locationIndex);
        }
    }

    private void ExitRoom(int locationIndex)
    {
        if (locationIndex != GameData.GetInstance().locationIndex)
        {    
            GameRoomModel.GetInstance().GetPlayerFromPlayerDic(locationIndex).ExitRoomDeleteHead();
            GameRoomModel.GetInstance().RemovePlayerFromPlayerDic(locationIndex);

            if (GameRoomModel.GetInstance().RoomState == 0)
            {
                CheckReadyAndStartBtnState();
                CheckInviteBtnState();
            }
        }
        else
        {
            if (GameObject.Find("GameRoomPage(Clone)"))
                GameController.GetInstance().DeleteAllExceptGameHall();
        }
    }
}
